import Constants from "../libs/Constants";
import { GameEvent } from "../libs/GameEvent";
import GameManager from "./GameManager";
import Stosh from "./Stosh";

// author : lamyoung
const { ccclass, property } = cc._decorator;



@ccclass
export default class DrawParabola extends cc.Component {

    
    @property(cc.Prefab)
    stosh: cc.Prefab = null;
   
    private _graphic: cc.Graphics = null;
    private _parabolaTrace : Array<cc.Vec2> = new Array();


    private _linearVelocity: cc.Vec2 = new cc.Vec2(0, 0);

    protected onLoad(): void {
        this._graphic = this.node.getComponent(cc.Graphics);
    }

    protected onEnable(): void {
        GameEvent.on(Constants.StageEvent.DrawParabola, this.drawParabola, this)
        GameEvent.on(Constants.StageEvent.ClearParabola, this.clearParabola, this)
        GameEvent.on(Constants.StageEvent.CastStosh, this.castStosh, this)

    }

    private drawParabola(offset: cc.Vec2) {
        if(this._graphic){
            this._graphic.clear();
            this._parabolaTrace = new Array();
            this._linearVelocity = new cc.Vec2(-offset.x*10 , Math.abs(offset.y)*10);
            // console.log("当前偏移量", this._linearVelocity.x,this._linearVelocity.y)
            const dt = 0.05;
            for (let count = 0; count < 100; count++) {
                let time = dt * count;
                // s = v_x * t
                let dx = this._linearVelocity.x * time;
                // h = v_y * t + 0.5 * a * t * t
                let dy = this._linearVelocity.y * time - 500 * time*time;
                // 当前时间点坐标
                let targetX =  dx;
                let targetY =  dy + 100;
                this._parabolaTrace.push(new cc.Vec2(this.node.x+targetX,this.node.y+targetY));
                // 坐标超过地板就不画了
                if (targetY < 0) break;
                this._graphic.circle(targetX, targetY, 8);
            }
            this._graphic.fill();
        }
        

    }


    clearParabola(){
        if(this._graphic){
            this._graphic.clear();
        }
       
    }

    castStosh() {
        let stosh = cc.instantiate(this.stosh);
        stosh.setParent(GameManager.instace.stoshs);
        GameEvent.emit(Constants.StageEvent.ChangePlayerAni,Constants.PlayerAniState.stosh)
        stosh.getComponent(Stosh)._parabolaTrace = this._parabolaTrace;
    }

    update() {
        if(GameManager.instace.gameIsStart && !GameManager.instace.gameIsOver){
            this.node.setPosition(GameManager.instace.player.position)
        }

    }

    onDisable(): void {
        GameEvent.off(Constants.StageEvent.DrawParabola, this.drawParabola, this)
        GameEvent.off(Constants.StageEvent.ClearParabola, this.clearParabola, this)
        GameEvent.off(Constants.StageEvent.CastStosh, this.castStosh, this)
    }

}
